<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% load staticfiles %}
    <!--引入JQuery-->
    <script type="text/javascript" src="{% static 'website/jquery-easyui/jquery-3.2.1.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'website/jquery-easyui/jquery.easyui.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'website/jquery-easyui/jquery.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'website/js/common.js' %}"></script>
    <script type="text/javascript" src="{% static 'website/jquery-easyui/locale/easyui-lang-zh_CN.js' %}"></script>
    <link rel="stylesheet" type="text/css" href="{% static  'website/jquery-easyui/themes/default/easyui.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static 'website/jquery-easyui/themes/icon.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static 'website/jquery-easyui/demo/demo.css' %}">
    <script>

        var ifInsert = undefined; // 用于标记行是否是新增还是修改
        var editIndex = undefined;     // 用于存储正在编辑行的索引
        var ID = undefined;     // 存放行自增ID

        // 用于存储记录行中处于编辑，还未保存的值
        var running_plan_name  = undefined; // 运行计划名称
        var project_type = undefined;      // 项目类型
        var project_id = null;              // 项目id
        var project_name = undefined;      // 项目名称
        var plan_id_list = [];           // 用于存储计划id
        var plan_name = undefined;         // 计划名称
        var script_dirpath = undefined;  // 自动化脚本所在父级目录
        var python_path = undefined;     // python程序安装目录
        var valid_flag = undefined; //是否启用
        var order = undefined; // 顺序

        function onLoadSuccess(data) {
            // 修改“操作”列的按钮样式
            $('.resetBtn').linkbutton({text:'重置状态', plain:true, iconCls:'icon-add'});
            $('.runBtn').linkbutton({text:'在线运行', plain:true, iconCls:'icon-add'});
            $('.insertRowBtn').linkbutton({text:'插入', plain:true, iconCls:'icon-add'});
            $('.editRowBtn').linkbutton({text:'修改', plain:true, iconCls:'icon-edit'});
            $('.deleteRowBtn').linkbutton({text:'删除', plain:true, iconCls:'icon-remove'});
            $('.moveUpBtn').linkbutton({text:'上移', plain:true, iconCls:'icon-edit'});
            $('.moveDownBtn').linkbutton({text:'下移', plain:true, iconCls:'icon-edit'});

            $('.saveRowBtn').hide();
            $('.cancelEditRowBtn').hide();

            editIndex = undefined;
            // 设置自动调整行高(主要是解决行号所在单元格和数据行错位问题)
            $('#Running_plan').datagrid('fixRowHeight');
        }


        // 格式化【操作】列
        function formatOperationColumn(value,row,index){
            var btn = "<a id='resetBtn" + index + "' class='resetBtn' onclick='setRunningPlanStatus(" + JSON.stringify(row) + "," +index+")' href='javascript:void(0)'>重置状态</a> \
                    <a id='runBtn" + index + "' class='runBtn' onclick='execRunningPlan(" + JSON.stringify(row) + "," +index+")' href='javascript:void(0)'>在线运行</a> \
                    <a id='insertRowBtn" + index + "' class='insertRowBtn' onclick='insertRow("+JSON.stringify(row) +"," + index+")' href='javascript:void(0)'>插入</a> \
                    <a id='editRowBtn" + index + "' class='editRowBtn' onclick='editRow(" + row.id +"," + index+")' \
                    href='javascript:void(0)'>修改</a>\
                    <a id='deleteRowBtn" + index + "' class='deleteRowBtn' onclick='removeRow(\"Running_plan\"," + row.id +"," + index+")' href='javascript:void(0)'>删除</a>\
                    <a id='moveUpBtn" + index + "' class='moveUpBtn' onclick='moveRow(\"Running_plan\"," + index+", this)' href='javascript:void(0)'>上移</a> \
                    <a id='moveDownBtn" + index + "' class='moveDownBtn' onclick='moveRow(\"Running_plan\"," + index+", this)' href='javascript:void(0)'>下移</a> \
                    <a id='saveRowBtn" + index + "' class='saveRowBtn' onclick='saveRow()' \
                     href='javascript:void(0)' style='display:none'>保存</a>\
                    <a id='cancelEditRowBtn" + index + "' class='cancelEditRowBtn' onclick='cancelEditRow(this)' \
                    href='javascript:void(0)' style='display:none'>取消</a>";
            return btn;
        }


        // 编辑时隐藏部分按钮
        function hideNoneEditBtn(editIndex) {
            $('#insertRowBtn' + editIndex).hide();
            $('#editRowBtn' + editIndex).hide();
            $('#deleteRowBtn' + editIndex).hide();
            $('#moveUpBtn' + editIndex).hide();
            $('#moveDownBtn' + editIndex).hide();
            $('#resetBtn' + editIndex).hide();
            $('#runBtn' + editIndex).hide();
            $('#viewReportBtn' + editIndex).hide();
            $('.saveRowBtn').linkbutton({text:'保存', plain:true, iconCls:'icon-ok'});
            $('.cancelEditRowBtn').linkbutton({text:'取消', plain:true, iconCls:'icon-cancel'});
            $('#saveRowBtn' + editIndex).show();
            $('#cancelEditRowBtn' + editIndex).show();
        }

        // 点击表格“插入|新增”按钮事件函数实现
        function insertRow(row, rowIndex) {
            if (endEditing()) {
                if (rowIndex == undefined) { // 点击 新增 按钮
                    editIndex = 0;
                    order = '';
                } else { // 点击 插入 按钮
                    editIndex = rowIndex + 1;
                    order = row.order
                }


                $('#Running_plan').datagrid('insertRow',{
                    index: editIndex,
                    row: { }
                });

                hideNoneEditBtn(editIndex);

                $('#Running_plan').datagrid('unselectAll');
                var row = $('#Running_plan').datagrid('selectRow', editIndex);
                $(row).datagrid('beginEdit', editIndex);

                // 初始化行组件值
                initDataForRowComponets('API项目', '新增');
                ifInsert = true;
            }
        }

        function initDataForRowComponets(projectType, opType,  projectIDList, planIDList, projectID, planName) {
            var projectNameEditor =  $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'project_name'});
            var validFlagEditor = $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'valid_flag'});
            var planNameEditor = $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'plan_name'});
            var scriptDirpathEditor = $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'script_dirpath'});
            var pythonPathEditor  = $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'python_path'});

            var defaultProjectType = projectType;
            if (projectType == 'UI项目') {
                projectType = 'UIProject';
            } else if(projectType == 'API项目'){
                projectType = 'APIProject';
            } else {
                return;
            }

            // 加载是否启用计划
            $(validFlagEditor.target).combobox('loadData',[{'id':'0','choice':'禁用'},{'id':'1','choice':'启用'}]);


            if (opType == '新增') {
                // 设置默认项目类型
                var projectTypeEditor =  $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'project_type'});
                $(projectTypeEditor.target).combobox('setText', defaultProjectType);

                // 设置默认启用计划
                $(validFlagEditor.target).combobox('setText', '启用');

                // 请求项目名称下拉列表数据
                getProjects(projectType).then(function(jsonData) {
                    if (jsonData['result'] == 'success') {
                        $(projectNameEditor.target).combobox('loadData', jsonData['data']);
                    } else {
                        $.messager.alert('错误信息', '获取项目失败：' + jsonData['data'], 'error');
                    }
                });

            } else if (opType == '修改') {
                // 做这一步是为了让项目名称已选文本值和下拉列表中的选项关联
                $(projectNameEditor.target).combobox('setValues', projectIDList);

                // 请求项目名称下拉列表数据
                getProjects(projectType).then(function(jsonData) {
                    if (jsonData['result'] == 'success') {
                        $(projectNameEditor.target).combobox('loadData', jsonData['data']);

                        // 必须等待获取项目成功后才进行以下操作，否则可能因为异步请求，清空下述操作的结果
                        getPlans(projectType, projectID).then(function(jsonData) {
                            if (jsonData['result'] == 'success') {
                                $(planNameEditor.target).combobox('setText', planName);
                                $(planNameEditor.target).combobox('loadData', jsonData['data']);
                                $(planNameEditor.target).combobox('setValues', planIDList);
                            } else {
                                $.messager.alert('错误信息', '获取计划名称失败：' + jsonData['data'], 'error');
                            }
                        });

                    } else {
                        $.messager.alert('错误信息', '获取项目失败：' + jsonData['data'], 'error');
                    }
                });
            } else if (opType == '切换项目类型') {
                getProjects(projectType).then(function(jsonData) {
                    if (jsonData['result'] == 'success') {
                        $(projectNameEditor.target).combobox('clear');
                        $(projectNameEditor.target).combobox('loadData', jsonData['data']);
                    } else {
                        $.messager.alert('错误信息', '获取项目失败：' + jsonData['data'], 'error');
                    }
                });
            }
            if (projectType == 'APIProject') {
                pythonPathEditor.target.val('');
                pythonPathEditor.target.attr('disabled', true);
                scriptDirpathEditor.target.val('');
                scriptDirpathEditor.target.attr('disabled', true);
            } else {
                pythonPathEditor.target.attr('disabled', false);
                scriptDirpathEditor.target.attr('disabled', false);
            }
        }

        // 点击 保存 按钮的函数实现
        function saveRow(){
            if (editIndex == undefined) {
                $.messager.alert('提示', '操作失败，没有正在编辑的记录', 'info');
                return;
            }
            if ($('#Running_plan').datagrid('validateRow', editIndex)){
                $('#Running_plan').datagrid('endEdit', editIndex);

                var isValid = true;
                if (project_name == '') {
                    $.messager.alert('提示','保存失败，项目名称不能为空', 'warnging');
                    isValid = false;
                } else if (plan_name == '') {
                    $.messager.alert('提示','保存失败，计划名称不能为空', 'warnging');
                    isValid = false;
                }

                if (!isValid) {
                    ifInsert = undefined;
                    editIndex = undefined;
                    onLoadSuccess();
                    $('#Running_plan').datagrid('reload');
                    return;
                }

                plan_id_list = plan_id_list.toString();
                if (ifInsert == true) { // 新增
                    var url = '/action/addRunningPlan';
                    var params = {
                        running_plan_name:running_plan_name,
                        project_type:project_type,
                        project_id:project_id,
                        project_name:project_name,
                        plan_id:plan_id_list,
                        plan_name:plan_name,
                        script_dirpath:script_dirpath,
                        python_path:python_path,
                        valid_flag:valid_flag,
                        order:order
                    };
                } else if (ifInsert == false) { // 修改
                    var url = '/action/updateRunningPlan';
                    var params = {
                        id:ID,
                        running_plan_name:running_plan_name,
                        project_type:project_type,
                        project_id:project_id,
                        project_name:project_name,
                        plan_id:plan_id_list,
                        plan_name:plan_name,
                        script_dirpath:script_dirpath,
                        python_path:python_path,
                        valid_flag:valid_flag
                    };
                }

                $.post(url, params, function(data,status){
                            if (data == 'success') {
                                $.messager.alert('提示','保存成功', 'info');
                            } else {
                                $.messager.alert('错误', data, 'error');
                            }
                            $('#Running_plan').datagrid('reload');
                        }
                );
            } else {
                $.messager.alert('告警', '保存失败,请检查是否设置必填(必选)项', 'error');
                $('#Running_plan').datagrid('reload');
            }

            ifInsert = undefined;
            editIndex = undefined;
            plan_id_list = [];
            project_id = null;
            onLoadSuccess();
        }

        // 点击 取消 按钮的函数实现
        function cancelEditRow() {
            if (editIndex == undefined) {
                $.messager.alert('提示', '操作失败，没有正在编辑的记录', 'info');
                return;
            }
            $('#Running_plan').datagrid('endEdit', editIndex);
            $('#Running_plan').datagrid('reload', editIndex);

            ifInsert = undefined;
            editIndex = undefined;
            onLoadSuccess();
        }

        // 结束编辑
        function endEditing(){
            if (editIndex == undefined) {
                return true;
            } else {
                $.messager.alert('提示', '您还有记录未保存', 'warnging');
                return false;
            }
        }

        // 结束编辑时自动触发的事件函数实现
        function onEndEdit(index, row) {
            // 获取单元格中输入的内容
            running_plan_name = $(this).datagrid('getEditor', {index: index,field: 'running_plan_name'}).target.val();
            project_type = $(this).datagrid('getEditor', {index: index,field: 'project_type'}).target.combobox('getText');
            project_name = $(this).datagrid('getEditor', {index: index,field: 'project_name'}).target.combobox('getText');
            plan_name = $(this).datagrid('getEditor', {index: index,field: 'plan_name'}).target.combobox('getText');
            script_dirpath = $(this).datagrid('getEditor', {index: index, field:'script_dirpath'}).target.val();
            python_path =  $(this).datagrid('getEditor', {index: index, field:'python_path'}).target.val();
            valid_flag = $(this).datagrid('getEditor', {index: index,field: 'valid_flag'}).target.combobox('getText');
        }

        // 点击表格 修改 按钮的函数实现
        function editRow(rowID, index){
            if (endEditing()) {
                if (index == undefined) { // 点击表格上方的 修改 按钮
                    //获取选中行的数据  
                    var rowsChecked = $('#Running_plan').datagrid('getChecked');
                    if (rowsChecked.length < 1) {  //如果没有选中行，提示信息  
                        $.messager.alert("提示消息", "请选择要修改的记录！", 'info');
                        return;
                    } else if (rowsChecked.length > 1) {
                        $.messager.alert("提示信息", "每次只能选择一条记录！", 'info');
                        return;
                    }
                    editIndex = $('#Running_plan').datagrid('getRowIndex', rowsChecked[0]);
                    ID = rowsChecked[0].id;
                } else { // 点击记录行所在的 修改 按钮
                    ID = rowID;
                    editIndex = index;
                }

                hideNoneEditBtn(editIndex);

                $('#Running_plan').datagrid('unselectAll');
                var row = $('#Running_plan').datagrid('selectRow', editIndex);
                $(row).datagrid('beginEdit', editIndex);

                // 禁用项目类型，项目名称，计划名称 combobox
                var projectType = rowsChecked[0].project_type;
                var projectIDList = rowsChecked[0].project_id.toString().split(',');
                var projectID = rowsChecked[0].project_id;
                var planIDList = rowsChecked[0].plan_id.split(',');
                var planName = rowsChecked[0].plan_name;

                initDataForRowComponets(projectType, '修改', projectIDList, planIDList, projectID, planName)

                ifInsert = false;
            }
        }

        //选择项目名称下拉列表项时触发事件
        function onSelectForProjectTypeCombobox(row){
            var projectType = row.choice;
            if (projectType == '') { //通过这个判断，控制初始化顺序带来的字段不识别问题
                return;
            }
            // 初始化项目combobox下拉列表// 暂时不管是UI项目还是API项目，统一从UI项目配置表中读取
            initDataForRowComponets(projectType, '切换项目类型');
        }

        //选择项目名称下拉列表项时触发事件
        function onSelectForProjectCombobox(row) {
            project_id = row.id;

            var planEditor =  $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'plan_name'});
            var projectType =  $('#Running_plan').datagrid('getEditor', {index: editIndex, field: 'project_type'}).target.combobox('getText');

            // 初始化项目combobox下拉列表
            if (projectType == 'UI项目') {
                projectType = 'UIProject';
            } else if(projectType == 'API项目'){
                projectType = 'APIProject';
            }

            getPlans(projectType, project_id).then(function(jsonData) {
                if (jsonData['result'] == 'success') {
                    $(planEditor.target).combobox('clear');
                    $(planEditor.target).combobox('loadData', jsonData['data']);
                } else {
                    $.messager.alert('错误信息', '获取计划名称失败：' + jsonData['data'], 'error');
                }
            });

        }


        // 收起 计划名称 下拉列表框时触发的事件
        function onHidePanelForProjectCombobox(){
            // 设置commbox输入框的文本值
            var projectNameEditor = $('#Running_plan').datagrid('getEditor', {index: editIndex, field:'project_name'});
            $(projectNameEditor.target).combobox('setValue', project_id.toString().split(','));
        }


        // 下拉点选计划名称列表选项时触发的事件
        function onSelectForPlanCombobox(row) {
            var index = plan_id_list.indexOf(row.id);

            // 如果不存在，则添加记录id属性值到数组，否则移除数组
            if(index != -1) {
                plan_id_list.splice(index, 1);
            } else {
                plan_id_list.push(row.id);
            }
        }

        //取消计划名称列表项时触发事件
        function onUnselectForPlanCombobox(row) {
            var index = plan_id_list.indexOf(row.id.toString());
            if(index != -1) { // 如果被取消项的id值存在数组中，则移除对应id
                plan_id_list.splice(index, 1);
            }
        }

        // 收起 计划名称 下拉列表框时触发的事件
        function onHidePanelForPlanCombobox(){
            // 设置commbox输入框的文本值
            var planNameEditor = $('#Running_plan').datagrid('getEditor', {index: editIndex, field:'plan_name'});
            $(planNameEditor.target).combobox('setValue', plan_id_list);
        }


        // 重置运行状态
        function setRunningPlanStatus(row, index) {
            var runningPlanNum = row.running_plan_num;
            //$.messager.alert('提示', '请求成功，正在执行', 'info');
            $.post('/action/setRunningPlanStatus', {runningPlanNum:runningPlanNum}, function(data, status) {
                        $.messager.alert('提示', data, 'info');
                        $('#Running_plan').datagrid('reload');
                    }
            );
        }

        // 点击在线运行，打开tab页函数实现
        function execRunningPlan(row, index) {
            var projectType = row.project_type;
            if (projectType == 'API项目') {
                var url = '/pages/debugAPIRunningPlan';

                var tabID = row.running_plan_num;
                var title = 'run-' + row.running_plan_name;

                var currentTab = window.parent.$('#tabs') //获取tab页面
                if(currentTab.tabs('exists', title)){  // 如果tab已存在，则选中、激活tab
                    currentTab.tabs('select', title);
                } else{ //否则，添加tab
                    var iframe='<iframe scrolling="auto"  id="iframe-' +  tabID + '" frameborder="0"  src="'+url+'" style="width:100%;height:100%;"></iframe>';
                    currentTab.tabs('add',{
                        id: tabID,
                        title: title,
                        content: iframe,
                        closable: true
                    });
                }
            } else if (projectType == 'UI项目'){
                if (row.running_status == '正在运行') {
                    $.messager.alert('提示', '当前任务正在执行中，请等待任务完成或者重置运行状态后再重试', 'info');
                    return;
                }
                var runningPlanNum = row.running_plan_num;
                var scriptDirpath = row.script_dirpath;
                var pythonPath = row.python_path;
                var projectType = row.project_type;

                $.ajax({
                    type: "POST",
                    url:"/action/execRunningPlan",
                    contentType: "application/json",
                    data:JSON.stringify({"runningPlanNum":runningPlanNum, "scriptDirpath":scriptDirpath,
                        "projectType":projectType, "pythonPath":pythonPath}),
                    sync: false,
                    success: function(data){
                        $.messager.alert('提示', data, 'info');
                        $('#Running_plan').datagrid('reload');
                    },
                    error: function(data){
                        $.messager.alert('提示', '执行出错，错误码：' + data.status, 'info');
                    }
                });
            }
        }
    </script>
</head>

<body class="easyui-layout">
<div data-options="region:'center'" title="">
    <table class="easyui-datagrid" rownumbers="true" pagination="true" id="Running_plan"
           data-options="border:false,
                singleSelect:false,
                fit:true,
                collapsible: true,
                toolbar: toolbar, 
                rownumbers: true,
                pageSize: 25,    
                pageList: [25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100],        
                nowrap: false,
                url: '/action/getRunningPlans',
                method: 'get',
                onEndEdit:onEndEdit,
                onLoadSuccess:onLoadSuccess">
        <thead>
        <tr>
            <th data-options="field:'ck',checkbox:true, fitColumns:true"></th>
            <th data-options="field:'id', align: 'center', fitColumns:true">ID</th>
            <th data-options="field:'running_plan_num', align: 'center', fitColumns:true">运行计划编码</th>
            <th data-options="field:'running_plan_name', align: 'left', editor:{type:'text'}" width="250px">运行计划名称</th>
            <th data-options="field:'project_id', align: 'center', fitColumns:true, hidden:true">项目ID</th>
            <th data-options="field:'project_type', align: 'center', editor:{
                            type:'combobox',
                            options:{
                                valueField:'id',
                                textField:'choice',
                                required:true,
                                editable:false,
                                panelHeight:'auto',
                                data:[{id:1, choice:'UI项目'},{id:2, choice:'API项目'}],
                                onSelect: onSelectForProjectTypeCombobox
                            }}" width="70px">项目类型</th>
            <th data-options="field:'project_name', align: 'left', editor:{
                            type:'combobox',
                            options:{
                                valueField:'id',
                                textField:'choice',
                                required:true,
                                editable:true,
                                panelHeight:'auto',
                                onSelect: onSelectForProjectCombobox,
                                onHidePanel:onHidePanelForProjectCombobox,
                            }}" width="300px">项目名称</th>
            <th data-options="field:'plan_id', align: 'center', fitColumns:true, hidden:true">计划ID</th>
            <th data-options="field:'plan_name', align: 'left', editor:{
                            type:'combobox',
                            options:{
                                valueField:'id',
                                textField:'choice',
                                required:true,
                                editable:true,
                                multiple:'true',
                                panelHeight:'auto',
                                onSelect: onSelectForPlanCombobox,
                                onUnselect:onUnselectForPlanCombobox,
                                onHidePanel:onHidePanelForPlanCombobox,
                            }}" width="400px">计划名称</th>
            <th data-options="field:'script_dirpath', align: 'left', editor:{type:'text'}" width="400px">自动化脚本所在父级目录绝对路径</th>
            <th data-options="field:'python_path', align: 'left', editor:{type:'text'}" width="300px">Python.exe程序绝对路径</th>
            <th data-options="field:'valid_flag', align: 'center',fitColumns:true, editor:{
                            type:'combobox',
                            options:{
                                valueField:'id',
                                textField:'choice',
                                data:[{id:0,choice:'禁用'},{id:1,choice:'启用'}],
                                required:true,
                                panelHeight:'auto',
                                editable:false
                            }}">是否启用</th>
            <th data-options="field:'running_status', align: 'left'" width="60px">运行状态</th>
            <th data-options="field:'remark', align: 'left'" width="200px">失败原因备注</th>
            <th data-options="field:'operations', title:'操作', align: 'center',
                        formatter:function(value,row,index){return formatOperationColumn(value,row,index);}"
                width="480px">操作</th>
        </tr>
        </thead>
    </table>
</div>
<!--增加工具条-->
<script type="text/javascript">
    // 定义工具栏
    var toolbar = addToolbar('Running_plan');
</script>
</body>
</html>